//
//  queue.cpp
//  Cpp_Demo
//
//  Created by Robin Guo on 2017/9/25.
//  Copyright © 2017年 Robin Guo. All rights reserved.
//

#include "queue.hpp"

// 队列 先进后出 排队 实现方式多种
// [q_front] -> [] ... [] -> [q_back](空闲)
template<class T>
queue<T>::queue() {

    node<T> *n;
    n = new node<T>;
    if (!n) {
        abort();
    }
    n->next = NULL;
    q_front=q_back=n;
    qsize = 0;
}

template<class T>
queue<T>::~queue() {
    node<T> *cur;
    
    if (q_front) {
        
        cur = q_front;

        while (cur) {
            q_front = cur->next;
            delete cur;
            cur = q_front;
            
        }
    }
}

template<class T>
void queue<T>::push(T data) {
    node<T> *n;
//    n = new node<T>;
//    if(!n) abort();
//    q_back->data = data;
//    n->next = q_back;
//    q_back = n;
//    qsize++;
    
    q_back->data = data;
    
    n = new node<T>;		// 新增结点补上
    if (!n) abort();
    
//    n->next = q_back->next;	// 连进队列 这句话可无用 误导观众啊
    q_back->next = n;
    q_back = n;
    qsize++;
    
}

template<class T>
T queue<T>::pop() {
    if (q_front && q_front != q_back) {
        node<T> *cur = q_front;
        q_front = cur->next;
        T data = cur->data;
        delete cur;
        qsize--;
        return data;
    }
    return NULL;
}

template<class T>
T queue<T>::top(){
    return q_front->next->data;
}

template<class T>
bool queue<T>::isEmpty() {
    return qsize==0?true:false;
}

template<class T>
int queue<T>::size() {
    return qsize;
}

template<class T>
T queue<T>::front() {
    if (q_front && q_front != q_back) {
        return q_front->data;
    }else abort();
}


